package com.iyao_app.util;

import com.iyao_app.entry.IMUser;

import io.realm.Realm;
import io.realm.RealmResults;

/**
 * Created by tongxue on 2017/12/18.
 */

public class UserUtils {
    public static void addUser(final IMUser oldSqlEntity) {
        Realm realm = Realm.getDefaultInstance();
        IMUser imUser = realm.where(IMUser.class).equalTo("userId", oldSqlEntity.userId).findFirst();
        if (imUser == null) {
            realm.executeTransaction(new Realm.Transaction() {
                @Override
                public void execute(Realm realm) {
                    realm.insert(oldSqlEntity);
                }
            });
        } else {
            realm.executeTransaction(new Realm.Transaction() {
                @Override
                public void execute(Realm realm) {
                    realm.copyToRealmOrUpdate(oldSqlEntity);
                }
            });
        }

    }


    public static IMUser getUser(String id) {
        Realm realm = Realm.getDefaultInstance();
        IMUser fromRealm = null;
        IMUser imUser = realm.where(IMUser.class).equalTo("userId", id).findFirst();
        if (imUser != null) {
            fromRealm = realm.copyFromRealm(imUser);
        }
        realm.close();
        return fromRealm;
    }

    public static void deleteUserInfo() {
        Realm realm = Realm.getDefaultInstance();
        //先查找到数据
        final RealmResults<IMUser> userList = realm.where(IMUser.class).findAll();
        realm.executeTransaction(new Realm.Transaction() {
            @Override
            public void execute(Realm realm) {
                if (userList.size() > 0) {
                    userList.deleteFromRealm(0);
                }
            }
        });

        realm.close();
    }

    public static void clearDb() {
        deleteUserInfo();
    }
}
